<template>
  <div class="content">
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh" style="height: calc(100vh - 46px);overflow: auto;">
      <div class="header">
        <div class="headerMsg">
          <div>
            <van-uploader :after-read="afterRead" accept="image/*" :deletable="false">
              <img v-if="headerImage" :src="headerImage" alt="">
              <img v-else src="@/assets/images/mobileLogo.jpg" alt="">
            </van-uploader>

          </div>
          <div class="headerCon">
            <p>欢迎您：<span class="red">{{userData.mobile}}</span></p>
            <!-- <p>ID：105110</p> -->
            <p>等级：{{userData.levelName}}
              <van-icon name="question" @click="cash('/membership')" />
            </p>
          </div>
        </div>
        <van-row>
          <van-col span="14" offset="5" class="tac" @click="cash('/balance')">
            <p class="amt">{{common.formatAmount(userData.balanceAmt,2)}}</p>
            <p class="usdt">余额(USDT)</p>
          </van-col>
          <van-col span="5" class="tar">
            <div style="padding-bottom:.15rem">
              <van-button type="primary" size="mini" @click="cash('/topUp')">充值</van-button>
            </div>
            <div>
              <van-button type="primary" size="mini" @click="cash(`/cashWithdrawal`)">提现</van-button>
            </div>
          </van-col>
        </van-row>
      </div>
      <div class="pure_top">

      </div>
      <van-cell-group>
        <van-cell title="我的项目" is-link to="/projectList" />
        <van-cell title="我的团队" is-link to="/myTeam" />
        <van-cell title="帮助中心" is-link to="/helpCenter" />
        <van-cell title="联系客服" is-link to="/contactCustomer" />
        <van-cell title="如何晋升" is-link to="/promotion" />
      </van-cell-group>
    </van-pull-refresh>
  </div>
</template>
<script>
export default {
  data () {
    return {
      mobile: '15859526995',
      id: JSON.parse(localStorage.getItem('userInfo')).id,
      userData: {},
      isLoading: false,
      fileList: '',
      headerImage: localStorage.getItem('image'),
      files: {
        name: "",
        type: ""
      },
    }
  },
  methods: {
    afterRead (file) {
      this.fileList = file.file
      this.files.name = file.file.name; // 获取文件名
      this.files.type = file.file.type; // 获取类型
      this.imgPreview(this.fileList)
    },
    // 处理图片
    imgPreview (file) {
      let self = this;
      // 看支持不支持FileReader
      if (!file || !window.FileReader) return;
      if (/^image/.test(file.type)) {
        // 创建一个reader
        let reader = new FileReader();
        // 将图片2将转成 base64 格式
        reader.readAsDataURL(file);
        // 读取成功后的回调
        reader.onloadend = function () {
          // console.log(this.result);
          let result = this.result;
          let img = new Image();
          img.src = result;
          //判断图片是否大于500K,是就直接上传，反之压缩图片
          if (this.result.length <= 200 * 1024) {
            self.headerImage = this.result;
            self.headerImage = self.dataURLtoFile(self.headerImage)
            self.postImg(self.headerImage);
          } else {
            img.onload = function () {
              let data = self.compress(img);
              self.headerImage = data;
              let imgSelf = self.dataURLtoFile(self.headerImage)
              self.postImg(imgSelf);
            };
          }
        };
      }
    },
    // 压缩图片
    compress (img) {
      let canvas = document.createElement("canvas");
      let ctx = canvas.getContext("2d");
      //瓦片canvas
      let tCanvas = document.createElement("canvas");
      let tctx = tCanvas.getContext("2d");
      // let initSize = img.src.length;
      let width = img.width;
      let height = img.height;
      //如果图片大于四百万像素，计算压缩比并将大小压至400万以下
      let ratio;
      if ((ratio = (width * height) / 4000000) > 1) {
        // console.log("大于400万像素");
        ratio = Math.sqrt(ratio);
        width /= ratio;
        height /= ratio;
      } else {
        ratio = 1;
      }
      canvas.width = width;
      canvas.height = height;
      //    铺底色
      ctx.fillStyle = "#fff";
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      //如果图片像素大于100万则使用瓦片绘制
      let count;
      if ((count = (width * height) / 1000000) > 1) {
        // console.log("超过100W像素");
        count = ~~(Math.sqrt(count) + 1); //计算要分成多少块瓦片
        //      计算每块瓦片的宽和高
        let nw = ~~(width / count);
        let nh = ~~(height / count);
        tCanvas.width = nw;
        tCanvas.height = nh;
        for (let i = 0; i < count; i++) {
          for (let j = 0; j < count; j++) {
            tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh);
            ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
          }
        }
      } else {
        ctx.drawImage(img, 0, 0, width, height);
      }
      //进行最小压缩
      let ndata = canvas.toDataURL("image/jpeg", 0.1);
      tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
      return ndata;
    },
    //base64转为图片
    dataURLtoFile (dataurl) {
      var arr = dataurl.split(","),
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], this.files.name, {
        type: this.files.type
      });
    },
    //上传图片
    async postImg (file) {
      const url = '/member/fileUpload'
      let fd = new FormData()
      fd.append('uploadFile', file)
      let result = await this.request.fileRequest('POST', url, fd)
      if (result.code == 200) {
        this.headerImage = result.data
        localStorage.setItem('image', result.data)
        this.updateImg(this.headerImage)
      } else {
        this.$notify({ type: 'warning', message: result.msg });
      }
    },
    //修改头像
    async updateImg (img) {
      const url = '/member/update'
      let result = await this.request.mobileRequest('PUT', url, { image: img })
      if (result.code == 200) {
        this.$notify({ type: 'success', message: '头像修改成功' });
      } else {
        this.$notify({ type: 'warning', message: result.msg });
      }
    },
    //跳转路由
    cash (path) {
      this.$router.push(path)
    },
    //获取用户信息
    async userDetail () {
      const url = `/member/get/${this.id}`
      let result = await this.request.mobileRequest('GET', url)
      if (result.code == 200) {
        if (this.headerImage == '' || this.headerImage == null) {
          if (result.data.image) {
            this.headerImage = result.data.image
            localStorage.setItem('image', result.data.image)
          }
        }
        this.userData = result.data
        this.userData.mobile = this.userData.mobile.substring(0, 3) + '****' + this.userData.mobile.substring(7, 11)
        localStorage.setItem('userData', JSON.stringify(this.userData))
      } else {
        this.$notify({ type: 'warning', message: result.msg });
      }
    },
    //下拉刷新
    onRefresh () {
      setTimeout(() => {
        this.userDetail();
        this.$toast('刷新成功')
        this.isLoading = false;
      }, 500)
    }
  },
  created () {
    this.userDetail();
  }
}
</script>

<style scoped>
.pure_top {
  width: 100%;
  height: 0.8rem;
  position: relative;
  overflow: hidden;
  margin-top: -30px;
}
.pure_top::after {
  content: "";
  width: 110%;
  height: 0.8rem;
  position: absolute;
  left: -5%;
  top: 0;
  border-radius: 80% 80% 0% 0%;
  background: #fff;
}
.header {
  padding: 0.2rem 0.4rem 1rem 0.4rem;
  background: #e8bb57;
}
.headerCon {
  padding-left: 0.4rem;
  font-size: 0.36rem;
  color: #555;
}
.content .van-cell {
  padding: 0.5rem 0.2rem;
}
.content .van-cell__title,
.van-cell__value {
  font-size: 0.38rem;
  color: #000;
  margin-left: 0.4rem;
}
.headerMsg {
  height: 2.2rem;
  display: flex;
  align-items: center;
}
.headerMsg img {
  width: 50px;
  height: 50px;
  border-radius: 100%;
}
.headerMsg div {
  display: flex;
  flex-direction: column;
}
p {
  line-height: 0.55rem;
}
.tac .amt {
  font-size: 0.5rem;
  padding-bottom: 0.15rem;
  color: #ff5722;
}
.usdt {
  font-size: 0.45rem;
  color: #555;
}
</style>
